package cn.xiyun.xiyuncc.MQ.consumer;

import cn.xiyun.xiyuncc.domain.CourseOrder;
import cn.xiyun.xiyuncc.dto.KillOrderDto;
import cn.xiyun.xiyuncc.service.ICourseOrderService;
import cn.xiyun.xiyuncc.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import lombok.SneakyThrows;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(
        consumerGroup = "KIllOrder_TimeOut_group",
        topic = "KIllOrderTimeOut_topic",
        selectorExpression = "KIllOrderTimeOut_tags",
        messageModel = MessageModel.BROADCASTING
)
public class KillOrderTimeOutConsumer implements RocketMQListener<String> {
    @Autowired
    private ICourseOrderService courseOrderService;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @SneakyThrows
    @Override
    public void onMessage(String killOrderDto)  {
        KillOrderDto killOrderDto1 = JSON.parseObject(killOrderDto, KillOrderDto.class);
        Wrapper<CourseOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no", killOrderDto1.getOrderNo());
        // 根据订单号查询 订单
        CourseOrder courseOrder = courseOrderService.selectOne(wrapper);
        if (courseOrder == null) return;
        // 判断订单状态,未支付则自动取消
        if (courseOrder.getStatusOrder() == CourseOrder.ORDER_UNPAID) {
            courseOrder.setStatusOrder(CourseOrder.ORDER_AUTO_CANCEL);
            courseOrderService.updateById(courseOrder);
            //TODO  给秒杀商品退回数量
            RSemaphore semaphore = redissonClient.getSemaphore(killOrderDto1.getKillCourseId().toString());
            int availablePermits = semaphore.availablePermits();
            redisTemplate.delete(killOrderDto1.getKillCourseId().toString());
            //设置信号量
            boolean setPermitsSuccess = semaphore.trySetPermits(availablePermits+1);
            AssertUtil.isTrue(setPermitsSuccess,"系统异常请稍后重试");
        }
    }
}
